﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using FrameWork.Components;
using System.Collections;
using Slja.Model.Platform;
using Slja.Utility;
using System.Net.Configuration;
using System.Web.Configuration;
using System.Net.Mail;
using System.Text;
using System.Runtime.Remoting.Contexts;
using Slja.Model;
using FrameWork.web.Web.UC;
using System.Configuration;
using Slja.BLL.Platform;


namespace FrameWork.web.Web
{
    public class WebCommon: System.Web.SessionState.IRequiresSessionState
    {
        public static void SendMail(string[] Recivers,string[] CC,string MailTitle,string MailBody,List<OrderFilesModel> AttFiles)
        {
            // addresses for send email.
            //string[] address = new string[] { "lnhndx@hotmail.com", "ln1023@gmail.com" };
            // email body.
            //string emailBody = "Hello! Guys!测试邮件发送Body";
            // email subject.
            //string subject = "这是测试邮件!";
            // get the config info.
            SmtpSection smtpSection = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~/web.config")).MailSettings.Smtp;
            // save the mail object.
            MailMessage mm = new MailMessage();
            foreach (string item in Recivers)
            { mm.To.Add(item); }
            mm.From = new MailAddress(smtpSection.From);
            //抄送
            foreach (string it in CC)
            { mm.CC.Add(it); }
            
            //密送
            //mm.Bcc.Add();

            mm.BodyEncoding = System.Text.Encoding.UTF8;
            mm.SubjectEncoding = System.Text.Encoding.UTF8;
            mm.IsBodyHtml = true;
            mm.Body = MailBody;
            mm.Subject = MailTitle;

            //内联图片
            //Attachment att1 = new Attachment(attpath);
            //att1.ContentId = "att1";
            //att1.ContentDisposition.Inline = true;
            //att1.NameEncoding = Encoding.UTF8;
            //mm.Attachments.Add(att1);
            //mm.Body += string.Format(@"<br><img src=""{0}""/>","cid:"+att1.ContentId);
            //附件
            string attpath="";
            //= HttpContext.Current.Server.MapPath("/uploadfile/PAA126001_04_title782.jpg");
            
            //附件
            for (int i = 0; i < AttFiles.Count; i++)
            {
                OrderFilesModel file = AttFiles[i];
                
                attpath = HttpContext.Current.Server.MapPath(file.Path);              
                
                Attachment att1 = new Attachment(attpath);
                att1.NameEncoding = Encoding.UTF8;
                mm.Attachments.Add(att1);
            }
            // set and send email.
            SmtpClient sc = new SmtpClient(smtpSection.Network.Host);
            sc.DeliveryMethod = SmtpDeliveryMethod.Network;
            sc.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
            sc.Send(mm);

        }
        public static UserModel GetDefaultFixAssistant()
        {
            string strUser = ConfigurationManager.AppSettings["Default_FixAssistant"];
            int FixAssiID;
            if (int.TryParse(strUser, out FixAssiID))
            {
                UserBLL bll = new UserBLL();
                return bll.GetModel(FixAssiID);
            }
            else
            {
                return null;
            }
        }
        public static UserModel GetDefaultOrderManager()
        {
            string strUser = ConfigurationManager.AppSettings["Default_OrderManager"];
            int OrderManager;
            if (int.TryParse(strUser, out OrderManager))
            {
                UserBLL bll = new UserBLL();
                return bll.GetModel(OrderManager);
            }
            else
            {
                return null;
            }
        }
        public static int GenerateNextStepPrincipal(Control Ctrl,OrderExtModel Order,Btn OpType,int Toward, out string UserName)
        {
            WorkTeam teamCtl;
            if (Order != null)
            {
                if(OpType == Btn.Submit)
                {
                    switch (Order.Enum_SaleState)
                    {
                            #region 不同的情况下，取得下一步的负责人
                        case SaleState.NewOrder://将执行：项目管理员提交
                            teamCtl = Ctrl.FindControl("WorkTeam1") as WorkTeam;
                            if (teamCtl != null)
                            {
                                UserName = teamCtl.DesignerName;
                                return teamCtl.DesignerID;
                            }                   
                            break;

                        case SaleState.AssignWork://将执行：设计提交
                            UserName = Order.ManagerUserName;
                            return Order.ManagerUser;

                        case SaleState.DesignUp://将执行：项目管理员，发送图纸
                             UserName = Order.ManagerUserName;
                            return Order.ManagerUser; 
                      
                        case SaleState.DesignSend://将执行：项目管理员，确认图纸
                            //合约
                            OrderWorkTeamModel contrac = Order.WorkTeam.Find(delegate(OrderWorkTeamModel md) { return md.enum_WorkRole == WorkerRole.OrderContracter; });
                            if (contrac != null)
                            {
                                UserName = contrac.WorkerName;
                                return contrac.WorkerID;
                            }
                            break;
                        case SaleState.DesignConfirm://将执行：报价
                            UserName = Order.ManagerUserName;
                            return Order.ManagerUser;
                        case SaleState.PriceUp://将执行：报价发送
                             UserName = Order.ManagerUserName;
                            return Order.ManagerUser;
                        case SaleState.PriceSend://将执行：报价确认
                            //项目管理
                            OrderWorkTeamModel fixAssi = Order.WorkTeam.Find(delegate(OrderWorkTeamModel md) { return md.enum_WorkRole == WorkerRole.FixAssistant; });
                            if (fixAssi != null)
                            {
                                UserName = fixAssi.WorkerName;
                                return fixAssi.WorkerID;
                            }
                            else
                            {   //取webconfig配置的工程助理
                                UserModel user = WebCommon.GetDefaultFixAssistant();
                                if (user != null)
                                {
                                    UserName = user.U_CName;
                                    return user.UserID;
                                }
                            }
                            break;
                            #endregion
                    }                    
                }                
            }
            throw new Exception("取得下一环节负责人失败");
        }
        public static UserModel CurrentUser
        {
            get{
                //将UserModel存入Session
                if (HttpContext.Current.Session["slja_current_user"] == null)
                {
                    Slja.BLL.Platform.UserBLL bll = new Slja.BLL.Platform.UserBLL();
                    Slja.Model.Platform.UserModel model = bll.GetModel(Common.Get_UserID);
                    HttpContext.Current.Session["slja_current_user"] = model;
                }
                return (UserModel)HttpContext.Current.Session["slja_current_user"];
             }
            
        }
        public static void AlertMsg(Page page, string Msg)
        {
           Msg= Regex.Replace(Msg, "'", "",RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
           string key = new Guid().ToString();
           ScriptManager.RegisterStartupScript(page, typeof(Page), key, "alert('" + Msg + "')",true);          

        }
        public static void GoMsgPage(string msg, MsgState state, string backUrl)
        {
            string URL = string.Format("/web/Message.aspx?msg={0}&type={1}&backurl={2}",
               HttpUtility.UrlEncode(msg), state.ToString(), HttpUtility.UrlEncode(backUrl));
            HttpContext.Current.Response.Redirect(URL);
        }
        public static List<string> GetRoleOrderTitle(int RoleID)
        {
            return new List<string>();
        }
        public static ArrayList GetProductTypeArraylist()
        {
            QueryParam qp = new QueryParam();
            qp.Where = string.Format("Where V_F_Key='{0}'", "ProductType");
            qp.Orderfld = " V_ShowOrder ";
            qp.OrderType = 0;
            ArrayList lst = new ArrayList();
            int cout;
            lst = BusinessFacade.sys_FieldValueList(qp, out cout);
            return lst;
        }
        public static string NewPrjID(DateTime CreateDate, string ProductType)
        {
            string yy = CreateDate.Year.ToString().Substring(2, 2);
            Slja.BLL.OrderBLL bll = new Slja.BLL.OrderBLL();
            string maxPrjID = bll.GetMaxPrjID(CreateDate, ProductType);
            if (maxPrjID != "")
            {
                string sufNumberStr = Regex.Match(maxPrjID,"\\d{4}$").Value;
                int num = int.Parse(sufNumberStr) + 1;
                return ProductType + yy + num.ToString("0000");
            }
            else
            {
                QueryParam qp = new QueryParam();
                qp.Where = string.Format("Where V_F_Key='{0}'", "PrjIDStartNumber");
                qp.Orderfld = " V_ShowOrder ";
                qp.OrderType = 0;
                ArrayList lst = new ArrayList();
                int cout;
                lst = BusinessFacade.sys_FieldValueList(qp, out cout);                
                for (int i = 0; i < lst.Count; i++)
                {
                    sys_FieldValueTable fv = (sys_FieldValueTable)lst[i];
                    //new ListItem(fv.V_Text,fv.V_Code)
                    if (ProductType.ToUpper() == fv.V_Text.ToUpper()
                        && fv.V_Code.Substring(0, 2) == yy)
                    {
                        return fv.V_Text.ToUpper() + fv.V_Code;
                    }
                }
                return ProductType + yy + "0001";
            }
        }   

}
}